<!--
 * @Description:
 * @Author: Fengqin
 * @Date: 2021-06-22 11:24:19
 * @LastEditors: Morgan
 * @LastEditTime: 2021-07-02 19:45:19
-->
<template>
  <div>
    <div>
      <el-button class="btn" type="primary" plain @click="toAdd">添加</el-button>
    </div>

    <!-- 表单 -->
    <div class="product-list">

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        stripe
      >
        <el-table-column
          type="index"
          label="序号"
        />
        <el-table-column
          prop="id"
          label="栏目编号"
        />
        <el-table-column
          prop="name"
          label="名称"
        />
        <el-table-column prop="icon" label="图标" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 40px"
              :src="scope.row.icon"
              :preview-src-list="[scope.row.icon]"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="num"
          label="排序号"
        />
        <el-table-column
          label="操作"
          width="100px"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" class="green_info" @click="toEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" class="red_info" @click="toDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-div">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[ 2, 5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加的模态框 -->
    <div>

      <el-dialog :title="title" :visible.sync="visible" @close="toClose">
        <el-form ref="ruleForm" :model="form" :rules="rules" size="small">
          <!-- {{form}} -->
          <el-form-item label="栏目名称" prop="name" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>

          <el-form-item label="序号" :label-width="formLabelWidth">
            <el-input v-model.number="form.num" autocomplete="off" />
          </el-form-item>

          <el-form-item prop="icon" label="图标" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadFileURL"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>

        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="visible= false">取 消</el-button>
          <el-button type="primary" @click="toSave">确 定</el-button>
        </div>

      </el-dialog>
    </div>
  </div>
</template>

<script>
import { pageQuery, saveOrUpdate, deleteById } from '@/api/proCategory'
import { showFileURL, uploadFileURL } from '@/utils/config'

export default {
  data() {
    return {
      // 图标的上传
      showFileURL,
      uploadFileURL,

      // 表格展示的数据
      tableData: [],
      params: {
        page: 1,
        pageSize: 10
      },
      // 总条数
      total: 0,
      // 加载
      loading: false,
      // 模态框的显示与隐藏
      visible: false,
      // 表单数据
      form: {},
      // 表单控件标题的宽度
      formLabelWidth: '80px',
      // 模态框的标题
      title: '',
      // 图片
      imageUrl: '',
      // 校验规则
      rules: {
        name: [{
          required: true,
          message: '请输入栏目名称',
          trigger: 'blur'
        }],
        icon: [{
          required: true,
          message: '请上传封面图片'
        }]
      }

    }
  },
  computed: {},
  watch: {
    params: {
      handler() {
        this.queryCategoryData()
      },
      deep: true
    }
  },
  created() {
    //  发请求
    this.queryCategoryData()
  },
  mounted() {},
  methods: {
    //  获取产品分类数据
    async queryCategoryData() {
      const res = await pageQuery(this.params)
      // console.log(res);
      this.total = res.data.total
      this.tableData = res.data.list
    },
    // 每页显示的条数发生变化时的事件处理程序
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.params = {
        pageSize: val,
        page: 1
      }
      //  this.loading = false
    },
    //   当前页码发生变化时的事件处理程序
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.params.page = val
    },
    // 编辑按钮
    toEdit(row) {
      this.queryCategoryData()
      // 设置表单数据
      this.form = { ...row }
      this.imageUrl = this.form.icon
      this.title = '编辑栏目信息'
      this.visible = true
    },
    // 删除按钮
    toDelete(id) {
      // this.$notify.success({
      //     title: '成功',
      //     message:res.success,
      //     });
      // this.queryCategoryData();
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteById({ id })
        this.queryCategoryData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 重置表单验证
    toClose() {
      this.$refs.ruleForm.resetFields()
      // 超时调用,在多少毫秒之后执行这个函数
      // setTimeout(()=>{
      //      this.visible = false;
      // },100)
    },
    // 模态框确定按钮处理程序
    toSave() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          // 校验通过，做自己的业务
          // console.log("校验通过");
          const res = await saveOrUpdate(this.form)
          // 提示用户保存成功，关闭模态框
          this.$notify.success({
            title: '成功',
            message: res.success
          })
          this.queryCategoryData()
          // this.toClose();
          this.visible = false
        } else {
          // 校验不通过
          return false
        }
      })
    },
    // 添加按钮
    toAdd() {
      this.queryCategoryData()
      // 清空表单数据
      this.form = {}
      this.imageUrl = ''
      this.title = '添加栏目信息'
      this.visible = true
    },
    //  图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.icon = this.showFileURL + res.data.id
    },
    //  图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }

  }
}
</script>
<style scoped>
 .product-list{
     /* padding: 10px; */
     margin-top: 10px;
 }
</style>
